-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find the Shortest Path in Directed Acyclic Graph - (Weight taken automatically).cpp
88 lines (80 loc) · 2.13 KB
/
Find the Shortest Path in Directed Acyclic Graph - (Weight taken automatically).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <map>
#include <stack>
#include <vector>
#include <climits>
using namespace std;
class Graph {
private:
map <int, vector<pair<int, int>>> graph;
map <int, bool> visited;
map <int, int> distance;
stack <int> topoSort;
int w = 0;
void DFS(int u){
visited[u] = true;
for(auto v:graph[u]){
if(!visited[v.first]) DFS(v.first);
}
topoSort.push(u);
}
void path(int u){
distance[u] = 0;
int top, weightSum;
while(!topoSort.empty()){
top = topoSort.top();
if(distance[top] != INT_MAX){
for(auto v:graph[top]){
int weightSum = distance[top] + v.second;
if(weightSum < distance[v.first])
distance[v.first] = weightSum;
}
}
topoSort.pop();
}
}
public:
void addEdge(int u, int v){
graph[u].push_back(make_pair(v, ++w));
graph[v];
}
void print(){
for(auto u:graph){
cout << "[" << u.first << "] => ";
for(int i = 0; i < u.second.size(); i++){
cout << (i == 0 ? "[" : ", ");
cout << "{" << u.second[i].first << ", " << u.second[i].second << "}";
if(i == u.second.size()-1) cout << "]";
}
cout << endl;
}
}
void shortestPath(int src){
DFS(src);
// Set infinity (∞) as default value for the distance map
for(auto u:graph)
distance[u.first] = INT_MAX;
path(src);
// Print Shortest
cout << endl << "Shortest Path from the " << src << " to N: ";
for(auto v:distance){
cout << ((v.second == INT_MAX) ? "∞" : to_string(v.second)) << " ";
}
cout << endl;
}
};
int main(){
Graph G;
G.addEdge(1, 2);
G.addEdge(1, 3);
G.addEdge(1, 4);
G.addEdge(2, 5);
G.addEdge(3, 8);
G.addEdge(4, 6);
G.addEdge(5, 8);
G.addEdge(6, 7);
G.addEdge(7, 8);
cout << "Adjacency List: " << endl;
G.print();
G.shortestPath(1);
}